package caser.cairngorm.services.async
{
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;

	public class RequestContainer extends ArrayCollection
	{
		public function findRequestByAsyncToken(asyncToken: AsyncToken): RequestContainerItem
		{
			for each (var request: RequestContainerItem in this)
				if (request.asyncToken == asyncToken) return request;
				
			return null;
		}
		public function findRequestByDataObject(dataObject: Object): RequestContainerItem
		{
			for each (var request: RequestContainerItem in this)
				if (request.dataObject == dataObject) return request;
				
			return null;
		}

		public function removeRequestByAsyncToken(asyncToken: AsyncToken): RequestContainerItem
		{
			var item: RequestContainerItem = this.findRequestByAsyncToken(asyncToken);
			if (item != null)
				return (this.removeItemAt(this.getItemIndex(item)) as RequestContainerItem);
			return null;
		}
		public function removeRequestByDataObject(dataObject: Object): RequestContainerItem
		{
			var item: RequestContainerItem = this.findRequestByDataObject(dataObject);
			if (item != null)
				return (this.removeItemAt(this.getItemIndex(item)) as RequestContainerItem);
			return null;
		}
		public function removeRequest(request: RequestContainerItem): RequestContainerItem
		{
			if (request != null)
				return this.removeRequestByAsyncToken(request.asyncToken);
			return null;
		}		

		public function addRequest(
			asyncToken: AsyncToken, 
			event: CairngormEvent,
			callBacks: ArrayCollection, 
			dataObject: Object): void
		{
			super.addItem(new RequestContainerItem(asyncToken, event, callBacks, dataObject));
		}
		override public function addItemAt(item: Object, index: int): void
		{
			if (!(item is RequestContainerItem)) throw new String("not supported type [should be RequestContainerItem]");
			super.addItemAt(item, index);			
		}
		
		
		public function RequestContainer()
		{
			super(null);
		}
		
	}
}